/* Declare app level module */
var SMS = angular.module('SMS', ['ngCookies', 'ngRoute']);
SMS.config(function ($routeProvider) {
    $routeProvider
        .when('/index', { redirectTo: '/library' })
        .when('/settings', { templateUrl: 'js/partials/settings.html', controller: 'SettingsController' })
        .when('/library', { templateUrl: 'js/partials/library.html', controller: 'SMSController' })
        .when('/playlists', { templateUrl: 'js/partials/playlists.html', controller: 'PlaylistController' })
        .otherwise({ redirectTo: '/index' });
})
.run(['$rootScope', '$location', 'globals', function ($rootScope, $location, globals) {
    $rootScope.$on("$locationChangeStart", function () {
        $rootScope.loggedIn = false;
        var path = $location.path().replace(/^\/([^\/]*).*$/, '$1');
        if (globals.settings.Username != "" && globals.settings.Password != "" && globals.settings.Server != "") {
            $rootScope.loggedIn = true;
        }
        if (!$rootScope.loggedIn && path != 'settings') {
            $location.path('/settings');
        }
    });
} ]);

SMS.service('model', function (utils) {
    this.Index = function (name, indexElement) {
        this.name = name;
        this.indexElement = indexElement;
    };
    this.Directory = function (id, parentid, name, coverArtThumb, coverArtFull)
    {
        this.id = id;
        this.parentid = parentid;
        this.name = name;
        this.coverArtThumb = coverArtThumb;
        this.coverArtFull = coverArtFull;
    };
    this.MediaElement = function (id, parentId, mediaType, suffix, duration, title, artist, album, genre, year, discNumber, discSubtitle, track, comment, coverArtThumb, coverArtFull, url, position) {
        this.id = id;
        this.parentId = parentId;
        this.mediaType = mediaType;
        this.suffix = suffix;
        this.duration = duration;
        this.time = duration === '' ? '00:00' : utils.secondsToTime(duration);
        this.title = title;
        this.artist = artist;
        this.album = album;
        this.genre = genre;
        this.year = year;
        this.discNumber = discNumber;
        this.discSubtitle = discSubtitle;
        this.track = track;
        this.comment = comment;
        this.coverArtThumb = coverArtThumb;
        this.coverArtFull = coverArtFull;
        this.url = url;
        this.position = position;
        this.selected = false;
        this.playing = false;
        this.displayName = this.title + " - " + this.album + " - " + this.artist;
    };
});

SMS.service('globals', function () {
    this.settings = {
        // SMS
        Url: "",
        Username: "",
        Password: "",
        Server: "",
        Timeout: 10000,
        NotificationTimeout: 20000,
        Protocol: "jsonp",
        AutoPlaylists: "",
        AutoPlaylistSize: 25,
        MediaBrowserListSize: 15,
        // General
        HideAZ: false,
        ScrollTitle: true,
        NotificationTrack: true,
        NotificationNowPlaying: false,
        SaveTrackPosition: false,
        ForceFlash: false,
        DefaultLibraryLayout: "grid",
        LoopQueue: false,
        Repeat: false,
        Debug: false
    };
    this.SavedCollections = [];
    this.BaseURL = function () { return this.settings.Server + '/rest'; };
    this.BaseParams = function () { return 'u=' + this.settings.Username + '&p=' + this.settings.Password + '&f=' + this.settings.Protocol + '&c=HTML5'; };
});

// Directives
SMS.directive('stopEvent', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attr) {
            element.bind(attr.stopEvent, function (e) {
                e.stopPropagation();
            });
        }
    };
});
SMS.directive('ngEnter', function () {
    return function (scope, element, attrs) {
        element.bind("keydown keypress", function (event) {
            if (event.which === 13) {
                scope.$apply(function () {
                    scope.$eval(attrs.ngEnter);
                });

                event.preventDefault();
            }
        });
    };
});

/* Factory */
SMS.factory('json', function ($http) { // Deferred loading
    return {
        getCollections: function (callback) {
            $http.get('js/json_collections.js').success(callback);
        }
    };
});

/* Filters */
SMS.filter('capitalize', function () {
    return function (input) {
        return input.substring(0, 1).toUpperCase() + input.substring(1);
    };
});

SMS.service('notifications', function ($rootScope, globals) {
    var msgIndex = 1;
    this.updateMessage = function (msg, autohide) {
        if (msg != '') {
            var id = msgIndex;
            $('#messages').append('<span id=\"msg_' + id + '\" class="message">' + msg + '</span>');
            $('#messages').fadeIn();
            $("#messages").scrollTo('100%');
            var el = '#msg_' + id;
            if (autohide) {
                setTimeout(function () {
                    $(el).fadeOut(function () { $(this).remove(); });
                }, globals.settings.NotificationTimeout);
            } else {
                $(el).click(function () {
                    $(el).fadeOut(function () { $(this).remove(); });
                    return false;
                });
            }
            msgIndex++;
        }
    };
    this.requestPermissionIfRequired = function () {
        if (!this.hasNotificationPermission() && (window.webkitNotifications)) {
            window.webkitNotifications.requestPermission();
        }
    };
    this.hasNotificationPermission = function () {
        return !!(window.webkitNotifications) && (window.webkitNotifications.checkPermission() == 0);
    };
    var notifications = new Array();
    this.showNotification = function (pic, title, text, type, bind) {
        if (this.hasNotificationPermission()) {
            //closeAllNotifications()
            var popup;
            if (type == 'text') {
                popup = window.webkitNotifications.createNotification(pic, title, text);
            } else if (type == 'html') {
                popup = window.webkitNotifications.createHTMLNotification(text);
            }
            if (bind = '#NextTrack') {
                popup.addEventListener('click', function (bind) {
                    //$(bind).click();
                    $rootScope.nextTrack();
                    this.cancel();
                })
            }
            notifications.push(popup);
            setTimeout(function (notWin) {
                notWin.cancel();
            }, globals.settings.NotificationTimeout, popup);
            popup.show();
        } else {
            console.log("showNotification: No Permission");
        }
    };
    this.closeAllNotifications = function () {
        for (notification in notifications) {
            notifications[notification].cancel();
        }
    };
});
